package org.vsc.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;


public class RSAEncrypt {
    
    private static final String ALGORITHM   = "RSA";

    private static final String CIPHER_NAME = "RSA/ECB/PKCS1Padding";


    public static String decrypt(String content, String key) throws Exception {

        PrivateKey prikey = KeyManager.getPrivateKeyFromPKCS8();

        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.DECRYPT_MODE, prikey);

        InputStream ins = new ByteArrayInputStream(Base64.decodeBase64(content.getBytes()));
        ByteArrayOutputStream writer = new ByteArrayOutputStream();

        byte[] buf = new byte[128];
        int bufl;

        while ((bufl = ins.read(buf)) != -1) {
            byte[] block = null;

            if (buf.length == bufl) {
                block = buf;
            } else {
                block = new byte[bufl];
                for (int i = 0; i < bufl; i++) {
                    block[i] = buf[i];
                }
            }

            writer.write(cipher.doFinal(block));
        }

        return new String(writer.toByteArray(), "utf-8");
    }

    public static String encrypt(String content, String key) throws Exception {
        PublicKey pubkey = KeyManager.getPublicKeyFromX509();

        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, pubkey);

        InputStream inputReader = new ByteArrayInputStream(content.getBytes("utf-8"));
        ByteArrayOutputStream writer = new ByteArrayOutputStream();

        byte[] buf = new byte[100];
        int bufl;

        while ((bufl = inputReader.read(buf)) != -1) {
            byte[] block = null;

            if (buf.length == bufl) {
                block = buf;
            } else {
                block = new byte[bufl];
                for (int i = 0; i < bufl; i++) {
                    block[i] = buf[i];
                }
            }

            writer.write(cipher.doFinal(block));
        }

        return new String(Base64.encodeBase64(writer.toByteArray()));
    }

}
